package com.weiyirong99.crm.app.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.table.TableData;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.header.FalsifyHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.mmkv.MMKV;
import com.weiyirong99.crm.app.R;
import com.weiyirong99.crm.app.api.Url;
import com.weiyirong99.crm.app.base.BaseFragment;
import com.weiyirong99.crm.app.bean.OnePhoneBean;
import com.weiyirong99.crm.app.bean.PhoneDataBean;
import com.weiyirong99.crm.app.bean.PhoneNum;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

public class HomeFragment extends BaseFragment {
    private RelativeLayout rlTitle;
    private ImageView ivBack;
    private TextView tvTitle;
    private TextView combinedTvSupplierHomeTitle;
    private View combinedViewSupplierHomeSep;
    private SmartRefreshLayout supplierInquirySrlAnnounce;
    private ClassicsHeader classicHeader;
    private ClassicsFooter classicFooter;
    private TextView sumTalk;
    private TextView talkCall;
    private TextView talkPickup;
    private TextView sumDuration;
    private TextView durationCall;
    private TextView durationPickup;
    private TextView sumTrack;
    private TextView sumNumber;
    private String url;
    private ArrayList<PhoneNum> list = new ArrayList<>();
    private ArrayList<Integer> listSevenOut = new ArrayList<>();
    private ArrayList<Integer> listSevenIn = new ArrayList<>();
    private ArrayList<String> time = new ArrayList<>();
    private List<String> xValues = new ArrayList<>();
    private HashMap<String, List<Integer>> map = new HashMap<>();
    private SmartTable smartTable;
    private YAxis leftAxis;             //左侧Y轴
    private YAxis rightAxis;            //右侧Y轴
    private XAxis xAxis;                //X轴
    private Legend legend;              //图例
    private LimitLine limitLine;        //限制线
    private WebView webView;


    @Override
    public int bindLayout() {
        return R.layout.fragment_home;
    }

    @Override
    public View initView(View view) {
        rlTitle = (RelativeLayout) view.findViewById(R.id.rl_title);
        ivBack = (ImageView) view.findViewById(R.id.iv_back);
        tvTitle = (TextView) view.findViewById(R.id.tv_title);

        sumTalk = (TextView) view.findViewById(R.id.sum_talk);
        talkCall = (TextView) view.findViewById(R.id.talk_call);
        talkPickup = (TextView) view.findViewById(R.id.talk_pickup);
        sumDuration = (TextView) view.findViewById(R.id.sum_duration);
        durationCall = (TextView) view.findViewById(R.id.duration_call);
        durationPickup = (TextView) view.findViewById(R.id.duration_pickup);
        sumTrack = (TextView) view.findViewById(R.id.sum_track);
        sumNumber = (TextView) view.findViewById(R.id.sum_number);
        webView = (WebView) view.findViewById(R.id.webView);
        combinedTvSupplierHomeTitle = (TextView) view.findViewById(R.id.combined_tv_supplier_home_title);
        combinedViewSupplierHomeSep = (View) view.findViewById(R.id.combined_view_supplier_home_sep);
        supplierInquirySrlAnnounce = (SmartRefreshLayout) view.findViewById(R.id.supplier_inquiry_srl_announce);
        classicHeader = (ClassicsHeader) view.findViewById(R.id.classic_header);
//        classicFooter = (ClassicsFooter) view.findViewById(R.id.classic_footer);
        smartTable = (SmartTable) view.findViewById(R.id.smartTable);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), SearchActivity.class));
            }
        });
        supplierInquirySrlAnnounce.setEnableLoadMore(false);

        supplierInquirySrlAnnounce.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getOneData();
                getData();
            }
        });
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public void initData(Bundle bundle) {
        super.initData(bundle);
        getOneData();
        getData();

    }


    private void getOneData() {

        long id = MMKV.defaultMMKV().decodeInt("companyId");
        url = Url.BaseUrl + "/api/company/" + id + "/mobile_today_analyze";
        Log.e("WG", "getData: " + url);
        OkGo.<String>get(url)
                .tag(getActivity())
                .headers("Authorization", MMKV.defaultMMKV().decodeString("token"))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("WG", "获取数据 " + response.body());
                        if (response.code() == 200) {
                            OnePhoneBean onePhoneBean = new Gson().fromJson(response.body(), OnePhoneBean.class);
                            sumTalk.setText("总通次：" + onePhoneBean.getCallCount());
                            talkCall.setText("拨打：" + onePhoneBean.getCallOutCount());
                            talkPickup.setText("接听：" + onePhoneBean.getCallInCount());
                            sumDuration.setText("总通时(s)：" + onePhoneBean.getCallDuration());
                            durationCall.setText("拨打(s)：" + onePhoneBean.getCallOutDuration());
                            durationPickup.setText("接听(s)：" + onePhoneBean.getCallInDuration());
                            sumTrack.setText("总跟进：" + onePhoneBean.getEventCount());
                            sumNumber.setText("跟进客户数：" + onePhoneBean.getEventCustomerCount());
                        } else {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body());
                                String message = jsonObject.getString("message");
                                Log.e("wg", "error: " + message);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("WG", "onError: ");

                    }
                });
    }

    private void getData() {


        Calendar calendar = Calendar.getInstance(TimeZone.getDefault());

        // 设置时间为当前日期的早上八点
        calendar.set(Calendar.HOUR_OF_DAY, 24);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        // 获取今天早上八点的时间戳
        long timestampThisMorning = calendar.getTimeInMillis();

        // 将日期回滚到上个月同一天的早上八点
        calendar.add(Calendar.MONTH, -1);
        long timestampLastMonthMorning = calendar.getTimeInMillis();


        Map<String, String> params = new HashMap<>();
        params.put("start", getTime(timestampLastMonthMorning));
        params.put("end", getTime(timestampThisMorning));
        long id = MMKV.defaultMMKV().decodeInt("companyId");
        url = Url.BaseUrl + "/api/company/" + id + "/mobile_total_analyze";
        Log.e("WG", "getData: " + url);
        OkGo.<String>get(url)
                .tag(getActivity())
                .headers("Authorization", MMKV.defaultMMKV().decodeString("token"))
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("WG", "获取电话总数 " + response.body());
                        if (response.code() == 200) {
                            if (list.size() > 0) {
                                list.clear();
                                listSevenOut.clear();
                                listSevenIn.clear();
                            }
                            try {
                                JSONArray jsonArray = new JSONArray(response.body());
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    Log.e("WG", "onSuccess: " + jsonArray.get(i));
                                    JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
                                    PhoneNum phoneNum = new PhoneNum();
                                    phoneNum.setDate(jsonObject.getString("date"));
                                    phoneNum.setCallCount(Integer.parseInt(jsonObject.getString("callCount")));
                                    phoneNum.setCallInCount(Integer.parseInt(jsonObject.getString("callInCount")));
                                    phoneNum.setCallOutCount(Integer.parseInt(jsonObject.getString("callOutCount")));
                                    list.add(phoneNum);
                                }
                                Collections.reverse(list);
                                for (int i = 0; i < list.size(); i++) {
                                    if (i < 7) {
                                        listSevenOut.add(list.get(i).getCallOutCount());
                                        listSevenIn.add(list.get(i).getCallInCount());
                                        time.add(list.get(i).getDate());
                                    }
                                }
                                PhoneDataBean phoneDataBean = new PhoneDataBean();
                                phoneDataBean.setPhoneOut(listSevenOut);
                                phoneDataBean.setPhoneIn(listSevenIn);
                                phoneDataBean.setTime(time);
                                String s = new Gson().toJson(phoneDataBean);
                                Log.e("WG", "onSuccess: " + s);
                                table();
                                setDatalist(s);
                                supplierInquirySrlAnnounce.finishRefresh(true);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        } else {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body());
                                String message = jsonObject.getString("message");
                                Log.e("wg", "error: " + message);
                                supplierInquirySrlAnnounce.finishRefresh(false);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("WG", "onError: ");

                    }
                });

    }




    private String getTime(long time) {
        // 将时间戳转换为Date对象
        Date date = new Date(time);

        // 创建SimpleDateFormat对象并设置日期格式
        // 注意：SimpleDateFormat不是线程安全的，所以最好在每个线程中创建新的实例
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区偏移量为+08:00
        // 格式化Date对象为字符串
        String formattedDate = sdf.format(date);

        // 拼接时区偏移量到日期字符串的末尾
        String finalFormattedDate = formattedDate + "+08:00";

        return finalFormattedDate;
    }

    private void table() {
        Column<String> column1 = new Column<>("日期", "date");
        Column<Integer> column2 = new Column<>("总通次", "callCount");
        Column<Integer> column3 = new Column<>("拨打", "callOutCount");
        Column<Integer> column4 = new Column<>("接听", "callInCount");

        //表格数据 datas是需要填充的数据
        final TableData<PhoneNum> tableData = new TableData<>("通话统计", list, column1, column2, column3, column4);
        //设置数据

        smartTable.setZoom(true);//是否缩放
        smartTable.setTableData(tableData);
        smartTable.getConfig().setShowXSequence(false);
        //X序号列
        smartTable.getConfig().setShowTableTitle(false);
//        //列标题
//        smartTable.getConfig().setFixedCountRow(true);
//        //统计行
//        smartTable.getConfig().setFixedTitle(true);

        smartTable.getConfig().setMinTableWidth(getScreenWidth(getActivity()));

    }

    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }


    private void setDatalist(String json) {

        webView.clearCache(true);
        CookieSyncManager.createInstance(getActivity());
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setBuiltInZoomControls(true); // 显示放大缩小 controler
        webSettings.setDisplayZoomControls(false);
        webSettings.setSupportZoom(true); // 可以缩放
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);// 默认缩放模式
        //加载需要显示的网页
        webSettings.setBlockNetworkImage(false);
        webSettings.setBlockNetworkLoads(false);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("file:///android_asset/lien.html?data=" + json);
    }


}

